<template>
  <div class="community-manage">
    <div class="search-container">
      <el-input
        placeholder="请输入小区名称"
        v-model="searchName"
        style="width: 200px;"
        suffix-icon="el-icon-search"
      ></el-input>
    </div>
    <div class="community-cards-container">
      <div class="community-cards">
        <div 
          v-for="(community, index) in filteredCommunities" 
          :key="community.communityId" 
          class="community-card"
        >
          <div class="card-header">
            <img 
              :src="getFirstImage(community.communityImage)" 
              alt="小区封面" 
              class="card-cover"
              @error="handleImageError"
            >
            <div class="card-info">
              <div class="community-name">{{ community.communityName }}</div>
              <div class="responsible-person">负责人：{{ community.communityPerson }}</div>
              <div class="phone">电话：{{ community.personPhone }}</div>
              <div class="address">地址：{{ getFullAddress(community) }}</div>
            </div>
          </div>
          <div class="card-actions">
            <a href="javascript:;" class="action-link" @click="renewCommunity(community)">续费</a>
            <a href="javascript:;" class="action-link" @click="editCommunity(community)">编辑</a>
            <a href="javascript:;" class="action-link delete-link" @click="deleteCommunity(community)">删除</a>
          </div>
        </div>
        
        <div v-if="filteredCommunities.length < 10" class="add-community-card" @click="showAddDialog">
          <div class="add-info">
            <i class="el-icon-plus"></i>
            <div class="add-text">添加小区</div>
            <div class="remain-text">当前还能添加{{ 10 - filteredCommunities.length }}个小区</div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog 
      :title="isEdit ? '编辑小区' : '新增小区'" 
      :visible.sync="dialogVisible" 
      width="50%"
      @close="handleDialogClose"
    >
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="小区名称" prop="communityName">
          <el-input v-model="form.communityName" placeholder="请输入小区名称"></el-input>
        </el-form-item>
        
        <el-form-item label="小区地址" prop="address">
          <el-select 
            v-model="form.province" 
            @change="handleProvinceChange"
            placeholder="选择省"
            style="width: 120px; margin-right: 10px;"
          >
            <el-option 
              v-for="province in provinces" 
              :key="province.code" 
              :label="province.name" 
              :value="province.name"
            />
          </el-select>

          <el-select 
            v-model="form.city" 
            @change="handleCityChange"
            placeholder="选择市"
            :disabled="!form.province"
            style="width: 120px; margin-right: 10px;"
          >
            <el-option 
              v-for="city in cities" 
              :key="city.code" 
              :label="city.name" 
              :value="city.name"
            />
          </el-select>

          <el-select 
            v-model="form.district" 
            placeholder="选择区"
            :disabled="!form.city"
            style="width: 120px; margin-right: 10px;"
          >
            <el-option 
              v-for="district in districts" 
              :key="district.code" 
              :label="district.name" 
              :value="district.name"
            />
          </el-select>

          <el-input 
            v-model="form.detailAddress" 
            placeholder="详细地址"
            style="width: 300px; margin-top: 10px;"
          />
        </el-form-item>

        <el-form-item label="负责人" prop="communityPerson">
          <el-input v-model="form.communityPerson" placeholder="请输入负责人姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="负责人电话" prop="personPhone">
          <el-input v-model="form.personPhone" placeholder="请输入负责人电话"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item label="小区图片">
          <el-upload
            action="/api/oss/upload"
            :on-success="handleImageSuccess"
            :before-upload="validateFileSize"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
          <div v-if="form.communityImage" class="image-preview">
            <img :src="getFirstImage(form.communityImage)" class="preview-image">
          </div>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CommunityManage',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入负责人电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      searchName: '',
      communities: [],
      dialogVisible: false,
      isEdit: false,
      currentEditId: '',
      
      form: {
        communityId: '',
        communityName: '',
        communityPerson: '',
        personPhone: '',
        communityAddress: '',
        communityImage: '',
        password: '',
        province: '',
        city: '',
        district: '',
        detailAddress: ''
      },
      
      rules: {
        communityName: [
          { required: true, message: '请输入小区名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        communityPerson: [
          { required: true, message: '请输入负责人姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        personPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ]
      },
      
      provinces: [],
      cities: [],
      districts: [],
      
      amapKey: '5cc13f6fd35f8e34b577d4ca2d8330cc'
    };
  },
  
  mounted() {
    this.getAllCommunities();
    this.getProvinces();
  },
  
  computed: {
    filteredCommunities() {
      if (!this.searchName) {
        return this.communities.slice(0, 10);
      }
      return this.communities.filter(community =>
        community.communityName.toLowerCase().includes(this.searchName.toLowerCase())
      ).slice(0, 10);
    }
  },
  
  methods: {
    getAllCommunities() {
      this.$axios.get('http://1localhost:8080/community/allcomm', { 
        params: { commName: this.searchName } 
      })
      .then(response => {
        console.log(response);
        if (response.data.code === 200) {
          this.communities = response.data.data || [];
        } else {
          this.$message.error('获取小区信息失败');
        }
      })
      .catch(error => {
        console.error('获取小区信息失败：', error);
        this.$message.error('获取小区信息失败');
      });
    },

    getProvinces() {
      this.$axios.get('https://restapi.amap.com/v3/config/district', {
        params: {
          key: this.amapKey,
          keywords: '中国',
          subdistrict: 1
        }
      }).then(res => {
        if (res.data.status === '1') {
          this.provinces = res.data.districts[0].districts.map(province => ({
            code: province.adcode,
            name: province.name.replace('省', '').replace('市', '').replace('自治区', '')
          }));
        }
      }).catch(error => {
        console.error('获取省份数据失败:', error);
      });
    },

    handleProvinceChange(provinceName) {
      this.form.city = '';
      this.form.district = '';
      this.cities = [];
      this.districts = [];
      
      const province = this.provinces.find(p => p.name === provinceName);
      if (province) {
        this.getCities(province.code);
      }
    },

    getCities(provinceCode) {
      this.$axios.get('https://restapi.amap.com/v3/config/district', {
        params: {
          key: this.amapKey,
          keywords: provinceCode,
          subdistrict: 1
        }
      }).then(res => {
        if (res.data.status === '1' && res.data.districts[0].districts) {
          this.cities = res.data.districts[0].districts.map(city => ({
            code: city.adcode,
            name: city.name.replace('市', '').replace('地区', '').replace('盟', '')
          }));
        }
      }).catch(error => {
        console.error('获取城市数据失败:', error);
      });
    },

    handleCityChange(cityName) {
      this.form.district = '';
      this.districts = [];
      
      const city = this.cities.find(c => c.name === cityName);
      if (city) {
        this.getDistricts(city.code);
      }
    },

    getDistricts(cityCode) {
      this.$axios.get('https://restapi.amap.com/v3/config/district', {
        params: {
          key: this.amapKey,
          keywords: cityCode,
          subdistrict: 1
        }
      }).then(res => {
        if (res.data.status === '1' && res.data.districts[0].districts) {
          this.districts = res.data.districts[0].districts.map(district => ({
            code: district.adcode,
            name: district.name.replace('区', '').replace('县', '').replace('市', '')
          }));
        }
      }).catch(error => {
        console.error('获取区县数据失败:', error);
      });
    },

    handleImageSuccess(response) {
      console.log(response);
      if (response.code === 200) {
        if (this.form.communityImage) {
          let images = [];
          try {
            images = JSON.parse(this.form.communityImage);
          } catch (e) {
            images = [this.form.communityImage];
          }
          images.push(response.data);
          this.form.communityImage = JSON.stringify(images);
        } else {
          this.form.communityImage = JSON.stringify([response.data]);
        }
        this.$message.success('图片上传成功');
      }
    },

    validateFileSize(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPGOrPNG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
        return false;
      }
      return true;
    },

    showAddDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetForm();
    },

    resetForm() {
      this.form = {
        communityId: '',
        communityName: '',
        communityPerson: '',
        personPhone: '',
        communityAddress: '',
        communityImage: '',
        province: '',
        password: '',
        city: '',
        district: '',
        detailAddress: ''
      };
      this.cities = [];
      this.districts = [];
      
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
    },

    submitForm() {
      this.$refs.formRef.validate(valid => {
        console.log(this.form);
        
        if (valid) {
          const url = this.isEdit 
            ? 'http://1localhost:8080/community/updatecomm' 
            : 'http://1localhost:8080/community/intocomm';
            
          const method = this.isEdit ? 'put' : 'post';
          
          this.$axios[method](url, this.form)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.isEdit ? '小区更新成功' : '小区添加成功');
                this.dialogVisible = false;
                this.getAllCommunities();
              } else {
                this.$message.error(response.data.message || '操作失败');
              }
            })
            .catch(error => {
              console.error('提交失败：', error);
              this.$message.error('操作失败');
            });
        }
      });
    },

    editCommunity(community) {
      this.isEdit = true;
      this.dialogVisible = false; // 先关闭对话框，确保数据加载后再打开
      
      // 填充表单数据
      this.form = {
        communityId: community.communityId,
        communityName: community.communityName,
        communityPerson: community.communityPerson,
        personPhone: community.personPhone,
        communityAddress: community.communityAddress,
        communityImage: community.communityImage,
        province: community.province,
        password: community.password,
        city: community.city,
        district: community.district,
        detailAddress: community.detailAddress
      };
      
      // 加载对应的城市和区县数据
      if (community.province) {
        const province = this.provinces.find(p => p.name === community.province);
        if (province) {
          this.getCities(province.code).then(() => {
            if (community.city) {
              const city = this.cities.find(c => c.name === community.city);
              if (city) {
                this.getDistricts(city.code);
              }
            }
          });
        }
      }

      // 确保数据加载后再打开对话框
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },

    handleDialogClose() {
      this.resetForm();
    },

    getFirstImage(imageData) {
      if (!imageData) return '/default-community.jpg';
      
      try {
        const images = JSON.parse(imageData);
        return Array.isArray(images) && images.length > 0 ? images[0] : '/default-community.jpg';
      } catch (e) {
        return imageData || '/default-community.jpg';
      }
    },

    handleImageError(event) {
      event.target.src = this.communities.communityImage;
      return;
    },

    getFullAddress(community) {
      const { province, city, district, detailAddress } = community;
      return [province, city, district, detailAddress].filter(Boolean).join('');
    },

    renewCommunity(community) {
      this.$message.info(`续费功能开发中，小区：${community.communityName}`);
    },

    deleteCommunity(community) {
      this.$confirm(`确定删除小区"${community.communityName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`http://1localhost:8080/community/delcomm/${community.communityId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.getAllCommunities();
            } else {
              this.$message.error(response.data.message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败：', error);
            this.$message.error('删除失败');
          });
      });
    }
  }
};
</script>

<style scoped>
.community-manage {
  padding: 30px;
  position: relative;
  max-width: 1400px;
  margin: 0 auto;
}

.search-container {
  position: absolute;
  top: 30px;
  right: 30px;
}

.community-cards-container {
  display: flex;
  justify-content: center;
  margin-top: 70px;
}

.community-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  width: 100%;
  max-width: 1200px;
  justify-content: flex-start;
}

.community-card {
  width: calc((100% - 60px) / 3);
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.community-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.card-cover {
  width: 200px;
  height: 150px;
  border-radius: 6px;
  margin-bottom: 15px;
  object-fit: cover;
}

.card-info {
  text-align: center;
  width: 100%;
}

.community-name {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 8px;
  color: #1f2937;
}

.responsible-person,
.phone,
.address {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
}

.card-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f3f4f6;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.2s;
  cursor: pointer;
}

.action-link:hover {
  color: #69b1ff;
  text-decoration: underline;
}

.delete-link {
  color: #f56c6c;
}

.delete-link:hover {
  color: #f78989;
}

.add-community-card {
  width: calc((100% - 60px) / 3);
  border: 1px dashed #d1d5db;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 330px;
  cursor: pointer;
  transition: border-color 0.2s, background-color 0.2s;
}

.add-community-card:hover {
  border-color: #409eff;
  background-color: #f9fafb;
}

.add-info {
  text-align: center;
}

.add-info i {
  font-size: 24px;
  color: #9ca3af;
  margin-bottom: 10px;
}

.add-text {
  margin: 8px 0;
  font-size: 16px;
  color: #4b5563;
}

.remain-text {
  font-size: 13px;
  color: #9ca3af;
}

.image-preview {
  margin-top: 10px;
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
